import Vue from "vue";
import Router from "vue-router";
import routes from "./routes";
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css'

import { get_token } from '@/utils/token'
import { get_info, set_info } from '@/utils/info'
import { user_info } from '@/api/auth'

Vue.use(Router);

const route = new Router({
  mode: 'history',
  routes
});

/**
 * 白名单
 */
const whiteList = ['/login', '/register']

/**
 * 前置钩子 （全局导航守卫）
 */
route.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  NProgress.start();
  let token = get_token();
  if (token) {
    if (to.path === '/login' || to.path === '/') {
      next({ path: '/home' });
      NProgress.done()
    } else {
      let info = get_info();
      if (!info) {
        user_info().then(res => {
          set_info(res);
          next();
          NProgress.done()
        })
      } else {
        next();
        NProgress.done()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
      NProgress.done()
    } else {
      // 否则全部重定向到登录页
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }

});

/**
 * 后置钩子
 */
route.afterEach(() => {
  // 结束Progress
  NProgress.done()
});


export default route;
